/**
 * 新增成长记录-教师、家长端
 * Created by xxx on 2017/7/13.
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'
import {
    HttpService,
    Tips,
    imgUpload,
    AjaxUploadImg,
    viewerImg,
    getClassList,
    taskFinish
} from '../Tools'

import Header from './Common/Header'
import Footer from './Common/Footer'
import ConfirmBox from './Common/ConfirmBox'

import addImg2 from '../Img/icon/add_img2.png'

export default class AddGrowthRecord extends Component {
    constructor(props) {
        super(props);
        this.imgfile = '';
        this.publish = false;
        this.state = {
            userrole: sessionStorage.userrole,
            classList: [],
            studentList: [],
            selectStudentList: [],
            stop: 0,
            isHaveImg: false,
            contentNumber: 0,
            footerList: false

        }
    }

    componentWillMount() {
        if (sessionStorage.userrole != '家长') {
            getClassList((classList) => {
                if (classList.length > 0) {
                    this.setState({
                        classList: classList
                    });
                    //查询班级学生
                    HttpService.query({
                        url: '/jxt-commonbackground/ajaxLoaderCommonUserInfo.do',
                        data: {
                            jybTicket: sessionStorage.ticket,
                            orgid: classList[0].id,
                            userrole: '学生',
                            method: 'ajaxJybJSON_LoadUserInfoByOrgIdAndUserRole'
                        },
                        async: false,
                        success: (res => {
                            if (res.code == 0) {
                                this.setState({
                                    studentList: res.rs
                                });
                                return;
                            }
                            Tips(res.msg);
                        })
                    });
                }
            });
        }
    }
    cfmCancel() {
        hashHistory.goBack(-1);
    }

    /**
     * 改变班级列表-查询班级学生
     */
    classChange(e) {
        let lists = document.querySelectorAll('.student_checkbox');
        for (let i = 0; i < lists.length; i++) {
            lists[i].checked = false;
        }
        HttpService.query({
            url: '/jxt-commonbackground/ajaxLoaderCommonUserInfo.do',
            data: {
                jybTicket: sessionStorage.ticket,
                orgid: e.target.value,
                userrole: '学生',
                method: 'ajaxJybJSON_LoadUserInfoByOrgIdAndUserRole'
            },
            async: false,
            success: (res => {
                if (res.code == 0) {
                    this.setState({
                        studentList: res.rs
                    });
                    document.querySelector('#students').value = '';
                    return;
                }
                Tips(res.msg);
            })
        })
    }

    /**
     * 获取学生
     */
    getStudentList() {
        let selectStudentList = this.state.selectStudentList;
        let student_checkboxs = document.querySelectorAll('.student_checkbox');
        for (let j = 0; j < student_checkboxs.length; j++) {
            student_checkboxs[j].checked = false;
        }
        if (selectStudentList.length > 0) {
            let lists = document.querySelector('.content_list').children;
            for (let j = 0; j < selectStudentList.split(',').length; j++) {
                for (let i = 0; i < lists.length; i++) {
                    let listsChild = lists[i].childNodes[0].childNodes;
                    let selectId = listsChild[0].defaultValue;
                    if (selectId == selectStudentList.split(',')[j]) {
                        listsChild[0].checked = true;
                        break;
                    }
                }
            }
        }
        this.setState({
            footerList: true
        });
    }

    /**
     * 选择学生列表-取消
     * @returns {XML}
     */
    cancelStudent() {
        this.setState({
            footerList: false
        });
    }

    /**
     *  选择学生列表-确定
     * @returns {XML}
     */
    addStudent() {
        if (this.state.studentList == '') {
            this.setState({
                selectStudentList: []
            });
        } else {
            this.state.selectStudentList = [];
            let selectIds = '',
                selectValues = '';
            let lists = document.querySelector('.content_list').children;
            for (let i = 0; i < lists.length; i++) {
                let listsChild = lists[i].childNodes[0].childNodes;
                let isSelect = listsChild[0].checked;
                if (isSelect) {
                    let selectId = listsChild[0].defaultValue;
                    let selectValue = listsChild[1].innerText;
                    selectIds += ',' + selectId;
                    selectValues += ',' + selectValue;
                }
            }
            if (selectIds.length > 0) {
                selectIds = selectIds.substr(1, selectIds.length);
                selectValues = selectValues.substr(1, selectValues.length);
            }
            document.querySelector('#students').value = selectValues;
            this.setState({
                selectStudentList: selectIds
            });
        }
        this.cancelStudent();

    }
    //图片上传的表单
    upLoadImg(inputId, imgId) {
        let rct = this;
        rct.setState({
            stop: 1
        });
        imgUpload({
            inputId,
            imgId,
            imgIeId: imgId,
        }, function(status, msg) {
            rct.setState({
                stop: 0,
                isHaveImg: true
            });
            if (status) {
                rct.imgfile = msg;
                document.querySelector('.upViewerImg').src = document.getElementById('upimg').src
            } else {
                Tips(msg);
                rct.imgfile = '';
                document.getElementById('upimg').src = addImg2;
            }
        });
    }

    /**
     * 清空img
     */
    closeIMg(e) {
        e.preventDefault();
        document.querySelector('#upimg').setAttribute('src', addImg2);
        document.querySelector('.upViewerImg').setAttribute('src', addImg2);
        this.setState({
            isHaveImg: false
        });
    }

    //提交数据
    postData(data) {
        HttpService.query({
            url: '/jxt-commonbackground/ajaxGrowup.do',
            data: data,
            //async: false,
            success: (res => {
                setTimeout(() => {
                    this.publish = false;
                }, 400)
                if (res.code == 0) {
                    Tips('发布成功！');
                    taskFinish('评价学生', (status, config) => {
                        if (status) {
                            this.config = config;
                            this.setState({
                                show: 1
                            })
                        } else {
                            hashHistory.goBack(-1);
                        }
                    })
                } else {
                    Tips(res.msg);
                }
            })
        })
    }

    /**
     * 发布
     */
    release() {
        if (this.publish)
            return
        let scoreNumber = document.querySelector('#scoreNumber').value; //评分
        let growthContent = document.querySelector('#growthContent').value; //成长记录内容
        let sendDate = this.getNowFormatDate().substr(0, 10);
        if (sessionStorage.userrole != '家长') {
            if (this.state.selectStudentList == '') {
                Tips('请选择学生');
                return;
            }
        }
        if (scoreNumber == '选择评分') {
            Tips('请选择评分');
            return;
        }
        if (growthContent == '') {
            Tips('请填写成长记录内容');
            return;
        }
        let data = {
            jybTicket: sessionStorage.ticket,
            czjlLevel: scoreNumber, //成长记录评分
            content: growthContent, //内容
            method: 'ajaxJybJSON_101AddCzjl',
            wherefrom: 'android',
            picid: null,
            sendDate: sendDate,
            type: 1
        };
        if (sessionStorage.userrole != '家长')
            data.studentids = this.state.selectStudentList
        this.publish = true;
        let rct = this;
        if (this.state.isHaveImg) {
            Tips('正在发布...', 0);
            AjaxUploadImg(this.imgfile, function(res) {
                if (res.status == 'ok') {
                    data.picid = '' + res.msg + '';
                    rct.postData(data)
                } else {
                    rct.publish = false;
                    Tips(res.msg);
                }
            })
        } else {
            this.postData(data)
        }
    }

    /**
     * 获取时间
     * @returns {string}
     */
    getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
            " " + date.getHours() + seperator2 + date.getMinutes() +
            seperator2 + date.getSeconds();
        return currentdate;
    }

    /**
     * 计算剩余输入字数
     * @returns {XML}
     */
    changeContentNumber(e) {
        this.setState({
            contentNumber: e.target.value.length
        });
    }
    render() {
        const {
            userrole,
            classList,
            studentList,
            isHaveImg,
            contentNumber,
            footerList
        } = this.state;
        const headerLink = <a className='h_link color-blue' onClick={this.release.bind(this)}>发布</a>;
        const classTagList = classList.map((item) => {
            return (
                <option value={item.id} dir="ltr">{item.name}</option>
            )
        });
        const studentLists = studentList.map((item) => {
            return (
                <li ><label className='cbx'><input type="checkbox" className="student_checkbox" value={item.id}/><span>{item.name}</span></label></li>
            )
        });
        return (
            <div className='add_growth_record'>
                <Header title='新增成长记录' link={headerLink}/> {userrole != '家长'
                    ? <div>
                            <label className="lt_hw_list lt_subject">
                                <span className="title">选择班级</span>
                                <div className="hw_right">
                                    <select name="classname" id="classname" dir="rtl" onChange={this.classChange.bind(this)}>
                                        {classTagList}
                                    </select>
                                </div>
                                <span className="input_right_img"/>
                            </label>
                            <div className="lt_hw_list lt_class_name">
                                <span className="title">选择学生</span>
                                <span className="img" onClick={this.getStudentList.bind(this)}/>
                                <div className="hw_right_bottom class_tare">
                                    <textarea cols="30" rows="2" id="students" readOnly='readOnly'  placeholder="请添加学生(可多选)"/>
                                </div>
                            </div>
                        </div>
                    : ''
                }

                <label className="lt_hw_list lt_subject">
                    <span className="title">选择评分</span>
                    <div className="hw_right">
                        <select name="scoreNumber" id="scoreNumber" dir="rtl">
                            <option value="选择评分" dir="ltr">选择评分</option>
                            <option value="7" dir="ltr">7</option>
                            <option value="6" dir="ltr">6</option>
                            <option value="5" dir="ltr">5</option>
                            <option value="4" dir="ltr">4</option>
                            <option value="3" dir="ltr">3</option>
                            <option value="2" dir="ltr">2</option>
                            <option value="1" dir="ltr">1</option>
                            <option value="0" dir="ltr">0</option>
                            <option value="-1" dir="ltr">-1</option>
                            <option value="-2" dir="ltr">-2</option>
                            <option value="-3" dir="ltr">-3</option>
                            <option value="-4" dir="ltr">-4</option>
                            <option value="-5" dir="ltr">-5</option>
                            <option value="-6" dir="ltr">-6</option>
                            <option value="-7" dir="ltr">-7</option>
                        </select>
                    </div>
                    <span className="input_right_img"/>
                </label>
                <div className="lt_hw_list lt_hw_content">
                    <span className="title">成长内容</span>
                    <div className="hw_right_bottom homewrk_tare">
                        <textarea name="" cols="30" id="growthContent" maxLength='50' onChange={this.changeContentNumber.bind(this)} placeholder="请填写成长内容(50字以内)"/>
                    </div>

                </div>
                <div className="img_word clearfix" >
                    <div className="hw_img_voice">
                        <div className="homewrk_tare_img" >
                            {/*<span className="icon_img"/>*/}
                            {/*<span className="title">添加照片</span>*/}
                            <label>
                                {
                                    isHaveImg == false?'':
                                    <span className="close" onClick={this.closeIMg.bind(this)}/>
                                }
                                <img src={addImg2} id='upimg' style={{display:isHaveImg == false?'block':'none'}}/>
                                <img src={addImg2} className='upViewerImg' style={{display:isHaveImg == true?'block':'none'}} onClick={viewerImg.bind(this,'src')} />
                                {
                                    isHaveImg==false?
                                        <input className='upcard hidden' name='front' type="file" id="upcard" accept="image/gif,image/jpeg,image/jpg,image/png" onChange={this.upLoadImg.bind(this, 'upcard', 'upimg')}/>
                                        :''
                                }
                            </label>
                        </div>
                    </div>
                    <div className="remaining_word_count">({contentNumber}/50)</div>
                </div>
                <div className="footer_List" style={{display: footerList == true?'inline-block':'none'}}>
                    <div className='maskin' onClick={this.cancelStudent.bind(this)}/>
                    <Footer>
                        <div className="content">
                            <div className="button clearfix">
                                <span className="cancel" onClick={this.cancelStudent.bind(this)}>取消</span>
                                <span className="ok" onClick={this.addStudent.bind(this)}>确定</span>
                            </div>
                            <ul className="content_list " id='pjb_cbxlist'>
                                {studentLists == ''
                                    ? <p>没有数据</p>
                                    : studentLists}
                            </ul>
                        </div>

                    </Footer>
                </div>
                <ConfirmBox config={this.config} show={this.state.show} cancel={this.cfmCancel.bind(this)}/>

                {stop == 1
                    ? <div className='mask'></div>
                    : ''
}
            </div>
        )
    }
}
